package com.interview.manytomany.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.interview.manytomany.entity.ManyOne;
import com.interview.manytomany.entity.ManyTwo;

@Repository
public class ManyToManyRepository {

	@PersistenceContext
	private EntityManager entityManager;

	public ManyOne findOne(String id) {
		return entityManager.find(ManyOne.class, id);
	}

	public void deleteOne(String id) {
		entityManager.remove(findOne(id));
	}

	public ManyOne saveOne(ManyOne manyOne) {
		entityManager.persist(manyOne);
		return manyOne;
	}

	public ManyOne updateOne(ManyOne manyOne) {
		return entityManager.merge(manyOne);

	}

	public ManyTwo findTwo(String id) {
		return entityManager.find(ManyTwo.class, id);
	}

	public void deleteTwo(String id) {
		entityManager.remove(findTwo(id));
	}

	public ManyTwo saveTwo(ManyTwo manyTwo) {
		entityManager.persist(manyTwo);
		return manyTwo;
	}

	public ManyTwo updateTwo(ManyTwo manyTwo) {
		return entityManager.merge(manyTwo);

	}

	public List<ManyOne> findOneAll() {

		String sql = "select * from one";

		Session session = (Session) entityManager.getDelegate();

		Query query = session.createSQLQuery(sql).addEntity(ManyOne.class);

		List<ManyOne> oneAll = query.list();

		return oneAll;
	}

	public List<ManyTwo> findTwoAll() {

		String sql = "select * from two";

		Session session = (Session) entityManager.getDelegate();

		Query query = session.createSQLQuery(sql).addEntity(ManyTwo.class);

		List<ManyTwo> twoAll = query.list();

		return twoAll;
	}

}
